<?php

namespace App\Http\Controllers;

use App\Model\Checkcategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Auth\User;
use Illuminate\Support\Facades\Redis;
use Maatwebsite\Excel\Facades\Excel;
use App\Services\XlSXWriter;

// use App\Model\Users;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */


    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = Auth::user();
//        dd($user);
        return redirect('/choose');

    }

    public function home()
    {
        // Auth::login($user,true);
        // $user = Users::where('id',285)->first();
        // var_dump(Redis::get('userid-11'));
        // var_dump(Redis::get('userid-12'));
        // var_dump(Redis::get('userid-13'));
        // Redis::setex('userid-11',30,'open'); 
        // Redis::setex('userid-12',20,'123'); 
        // Redis::setex('userid-13',10,'456'); 
        // Redis::sadd('set','set1');
        // Redis::sadd('set','set2');
        // Redis::sadd('set','set2');
        return view('home');
    }

    public function exportData($companyId){
        // 查询要导出数据的企业信息
        $company = Company::where('id',$companyId)->get()->toarray();

        $checkCatetory = CheckCategory::pluck('name','id')->toArray();
        // dd($company);
        // 查询对应公司下面的全部员工信息
        $content = Content::pluck('content','id');
        $department = Department::pluck('name','id');
        $users = User::where('companyId',$companyId)->get()->toArray();
        $userData = [];
        foreach($users as &$user)
        {
            $ouser = [];
            $zz = array();
            $where  = array('userid' => $user['id']);
            $contract =Contract::where($where)->orderBy('id','desc')->first();
            if($contract){
                    $pieces = explode(",", $contract['work_contentid']);
                    $k=count($pieces);
                    
                    for($i=0;$i<$k;$i++){
                        if($pieces[$i]){
                            $zz[$i]=$content[$pieces[$i]];
                        }
                    } 
            }
            $user['did'] =$department[$user['did']];
            $user['company'] = $company[0]['name'];
            $user['content'] =  implode(",", $zz);
            if($user['sex']==0){
                $user['sex'] ='男';
            }else{
                $user['sex'] ='女';
            }
            // 查询员工劳动合同相关信息
            $contractData = Contract::where('userid',$user['id'])->get()->toArray();
            // dd($user['id']);
            // 通过用户的contendid查询岗位信息
            $contendIds = explode(',',$user['contentid']);
            $cids = Content::whereIn('id',$contendIds)->pluck('fid');
            $cdata = Classification::whereIn('id',$cids)->pluck('name');
            
            $cname ='';
            if(!empty($cdata)){
                foreach($cdata as $cd){
                    $cname .= ','.$cd;
                }
            }else{
                $cname = '';
            }
            $ouser['id'] = $user['id'];//序号
            $ouser['user_id'] = isset($contractData[0]['id'])?sprintf("%011d",$contractData[0]['id']):'';//工号
            $ouser['name'] = $user['name'];//姓名
            $ouser['nationality'] = '';//民族
            $ouser['sex'] = $user['sex'];//性别
            $ouser['account'] = $user['account'];
            $ouser['create_time'] =!empty($contractData[0]['fixed_term_s'])? $contractData[0]['fixed_term_s']:'';//入职时间
            $ouser['record'] = '';//学历
            $ouser['graduate_institutions'] = '';//毕业院校
            $ouser['direction'] = '';//专业
            $ouser['graduate_date'] = '';//毕业时间
            $ouser['phone'] = !empty($contractData[0]['phone'])?$contractData[0]['phone']:'';//联系电话
            $ouser['bithday'] = '';//生日
            $ouser['b_registered'] = !empty($contractData[0]['b_registered'])?$contractData[0]['b_registered']:'';//籍贯
            $ouser['b_address'] = !empty($contractData[0]['b_address'])?$contractData[0]['b_address']:'';//现住址
            $ouser['email'] = $user['email'];//邮箱
            $ouser['did'] = $user['did'];//所在部门
            $ouser['operating_post'] = $cname;//工作岗位
            $ouser['content'] = $user['content'];//主要工作内容
            $userData[] = $ouser;

        }
        
        // dd($userData);													

        // 处理数据导出表格
        $search = [];
        // 表头
        $title = [
            '序号',
            '工号',
            '姓名',//name
            '民族',
            '性别',//sex
            '身份证号',//account
            '入职时间',
            '学历',
            '毕业学校',
            '所学专业',
            '毕业时间',
            '移动电话',
            '出生年月日',
            '籍贯',
            '现住址',
            '邮箱',
            '所在部门',//did
            '职务',
            '主要工作内容'//content
        ];
        foreach ($title as $key => $item){
            // if($key ==1){//如果是编号的话，指定数据类型为string，excel中则为文本类型
            //     $col_style[] = 'integer';
            // }else{
            // 	$col_style[] = 'string';
            // }
            $col_style[] = 'string';
        }
        // dd($col_style);
        $data = $userData;
        $writer = new XlSXWriter();
        $filename = date('Y').$company[0]['name'].'职工名册总表-'.date('YmdHis') . ".xlsx";             //文件名
        header('Content-disposition: attachment; filename="' . XLSXWriter::sanitize_filename($filename) . '"');
        header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        $colnum = count($title) - 1;                              //查询条件合并列数
        $sheet1 = date('Y').$company[0]['name'].'职工名册';                                     //工作簿名称
        $writer->writeSheetHeader($sheet1, $col_style, ['suppress_row'=>true,'widths'=>[10,30,15,10,5,20,20,20,20,20,20,20,20,20,20,20,20,20,40]] );//设置表头宽度工作簿名称
        if($company[0]['name']){//此处是如果需要单独显示标题头时，合并第一行的单元格
            $where = date('Y').$company[0]['name'].'职工名册';
            $writer->writeSheetRow(                                 //写入第一行的数据，顺便指定样式
                $sheet1,
                [$where],
                ['height' => 33, 'font-size' => 10, 'font-style' => 'bold',
                    'halign' => 'center', 'valign' => 'center', 'wrap_text' => true]
            );
            //合并单元格，第一行的搜索条件需要合并单元格
            $writer->markMergedCell($sheet1, $start_row = 0, $start_col = 0, $end_row = 0, $end_col = $colnum);
        }
        //设置标题头，指定样式
        $styles1 = array('height' => 20,'valign' => 'center','font' => '宋体', 'font-size' => 10, 'font-style' => 'bold', 'fill' => '#FFFFFF',
            'halign' => 'center', 'border' => 'left,right,top,bottom');
        $writer->writeSheetRow($sheet1, $title, $styles1);
        $styles2 = ['height' => 35];//设置单元格的高度
        foreach ($data as $row) {
            // 将单行数据写入表格中
            $writer->writeSheetRow($sheet1, $row, $styles2);

        }
        // 输出表格文件
        $writer->writeToStdOut();
        // 将文件保存到制定路径
        $writer->writeToFile(base_path().' /public/storage/'.$filename);
        exit();

}




    public function choose()
    {
        $user = Auth::user();
        return view('choose')
            ->with('name',$user->name)
            ->with('companyId',$user->companyId)
            ->with('type',$user->type);
    }
}
